#ifndef MPHTTPCONNECTIONMANAGETHREAD_H
#define MPHTTPCONNECTIONMANAGETHREAD_H

#include <boost/asio/connect.hpp>
#include "mpHttpConnectionManage.h"

#include "mpAppUtils.h"
#include "mpLog.h"


using namespace MP::HTTP;

class mpHttpConnectionManageThread
{
public:
    mpHttpConnectionManageThread()
        :_io_context()
    {
        _manage = createHttpConnectionManage(_io_context);
    }
    ~mpHttpConnectionManageThread(){
        _manage->clearAndDeactivate();
    }

    void exec_connect(boost::asio::io_context& context,
                      const std::string& host,
                      const std::string& port,
                      HttpConnection::ptr_s connection){

        boost::asio::ip::tcp::resolver resolver(context);
        boost::asio::ip::tcp::resolver::query query(host,port);
        boost::asio::ip::tcp::resolver::results_type endpoints = resolver.resolve(query);
        boost::system::error_code err;
        boost::asio::connect(connection->getHttpSocket(), endpoints,err);

        if(err){
            MPLOG_INFO << err.message();
        }
        else{
            connection->changeToConnect();
        }
    }

    void doCase1(std::size_t count,
                 std::string schema,
                 std::string host,
                 std::string port){

        SslSettings sslSettings;

        for(std::size_t i =0; i < count;i ++){

            HttpConnection::ptr_s connection = _manage->getHttpConnection(schema,host,port,sslSettings);
            if(connection){
                //执行连接
                exec_connect(_io_context,host,port,connection);
                MP::AppUtils::currentThreadWaiting(50);

                _manage->recoveryHttpConnection(connection);

                MPLOG_INFO << "Connection In Use Count :" << _manage->getConnectionInUseCount();
                MPLOG_INFO << "Connection In PoolCount :" << _manage->getConnectionInPoolCount();
            }
            MP::AppUtils::currentThreadWaiting(50);
        }
    }

private:
    boost::asio::io_context _io_context;
    HttpConnectionManage::ptr_s _manage;
};

#endif // MPHTTPCONNECTIONMANAGETHREAD_H
